package org.wishwork.api.product.common.query;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 普通商品资料查询（按sku查询）
 * @author: WangYX
 * @create: 2022-04-08 17:43
 * @Version: 1.0.0
 **/

public class CommonProductQueryApi extends Api<List<CommonProductQueryResponse>, CommonProductQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(CommonProductQueryApi.class);

    private Context context;

    public CommonProductQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(CommonProductQueryRequest commonProductQueryRequest) throws Exception {
        String url = "/open/sku/query";
        Map<String, Object> params = new HashMap<>();
        if (StrUtil.isNotEmpty(commonProductQueryRequest.getSkuIds())) {
            params.put("sku_ids", commonProductQueryRequest.getSkuIds());
        }
        return HttpHelper.sendRequest(commonProductQueryRequest, params, url);
    }

    @Override
    protected List<CommonProductQueryResponse> process(JSONObject data, CommonProductQueryRequest commonProductQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<CommonProductQueryResponse> commonProductQueryResponses = datas.toJavaList(CommonProductQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = commonProductQueryRequest.getPageIndex();
            CommonProductQueryRequest build = commonProductQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<CommonProductQueryResponse> business = business(build);
            commonProductQueryResponses.addAll(business);
        }
        return commonProductQueryResponses;
    }
}
